package com.zilue.hfqueue.channel;


import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * Created by ZD on 2017/6/2.
 */
public class PostHandler {
    private static String ip;

    static {
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
            ip = String.format("%-15s", ip);
        } catch (UnknownHostException e) {
            e.printStackTrace();
            ip = "000.000.000.000";
        }
    }

    public static boolean sendMessage(String topic, byte[] data,String host,int port) throws IOException {

        Message message = Message.builder().timestamp(System.currentTimeMillis()).data(data).ip(ip).id(UID.getLongUniqueId()).topic(topic).build();
        ByteBuffer writeBuffer = MessageHandler.byteBuffer(message);
        ByteBuffer readBuffer = ByteBuffer.allocate(64);

        SocketChannel channel = SocketChannel.open();
        channel.connect(new InetSocketAddress(host, port));
        while (writeBuffer.hasRemaining()) {
            channel.write(writeBuffer);
        }
        channel.shutdownOutput();
        int size = channel.read(readBuffer);
        channel.shutdownInput();
        channel.finishConnect();

        readBuffer.flip();
        int code = readBuffer.getInt();
        if (code == MessageStatus.success.getStatus())
            return true;
        byte[] array = new byte[size - Integer.BYTES];
        readBuffer.get(array);
        System.out.println("server response failed:" + code + new String(array, "utf-8"));
        return false;
    }
}
